package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.entity.User;
import com.sky.mapper.WxUserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.WxUserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;

@Slf4j
@Service("WxUserService")
public class WxUserServiceImpl implements WxUserService {
    private  WeChatProperties weChatProperties;
    private final WxUserMapper wxUserMapper;
    @Value("${sky.wechat.jscode2session_url}")
    private String session_url;
    @Autowired
    public WxUserServiceImpl(WxUserMapper wxUserMapper,WeChatProperties weChatProperties) {
        this.wxUserMapper = wxUserMapper;
        this.weChatProperties = weChatProperties;
    }

    @Override
    public User wxLogin(String code) throws IOException, LoginException {
        String openid = getOpenid(code);
        if(openid == null){
            throw new LoginException(MessageConstant.LOGIN_FAILED);
        }
        // 判断是否为新用户
        User user = wxUserMapper.queryUser(openid);
        if(user == null ){
            // 插入新用户
            user = User.builder()
                   .openid(openid)
                   .createTime(LocalDateTime.now())
                   .build();
           wxUserMapper.insetUser(user);
        }
        //   - 新用户完成注册
        // 老用户直接返回用户信息
        return user;
    }
    public String getOpenid(String code){
        HashMap<String, String> params = new HashMap<>();
        weChatProperties.getSecret();
        params.put("appid",weChatProperties.getAppid());
        params.put("secret",weChatProperties.getSecret());
        params.put("js_code",code);
        params.put("grant_type","authorization_code");
        String s = HttpClientUtil.doGet(session_url, params);
        JSONObject o =  JSONObject.parseObject(s);
        return o.getString("openid");
    }
}
